import axios from "axios";


const request = axios.create({
    timeout:20000
});


request.interceptors.request.use(function (config) {
    // Do something before request is sent
    //  把token放在请求头中携带过去
    config.headers["Authorization"] = "bearer" + localStorage.getItem("token")
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
request.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    console.log(error)
    if(error.response){
      const { status ,data} = error.response;
      switch(status){
        case 401:
          alert(data.msg);
          //  清除本地存储的token 和routes
          localStorage.removeItem("token");
          localStorage.removeItem("routes");
          window.location.href = "/";
        break;
      }
    }
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });


  export default request;


